package com.hai.video;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.ArrayMap;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private int[] mpStWhat = new int[]{1, 2, 3, 700, 701, 702, 703, 800, 801, 802, 803, 804, 805, 900, 901, 902};
    private String[] mpStStr = new String[]{"MEDIA_INFO_UNKNOWN", "MEDIA_INFO_STARTED_AS_NEXT"
            , "MEDIA_INFO_VIDEO_RENDERING_START", "MEDIA_INFO_VIDEO_TRACK_LAGGING", "MEDIA_INFO_BUFFERING_START"
            , "MEDIA_INFO_BUFFERING_END", "MEDIA_INFO_NETWORK_BANDWIDTH", "MEDIA_INFO_BAD_INTERLEAVING"
            , "MEDIA_INFO_NOT_SEEKABLE", "MEDIA_INFO_METADATA_UPDATE", "MEDIA_INFO_EXTERNAL_METADATA_UPDATE",
            "MEDIA_INFO_AUDIO_NOT_PLAYING", "MEDIA_INFO_VIDEO_NOT_PLAYING", "MEDIA_INFO_TIMED_TEXT_ERROR",
            "MEDIA_INFO_UNSUPPORTED_SUBTITLE", "MEDIA_INFO_SUBTITLE_TIMED_OUT"};
    private Map<Integer, String> map = new ArrayMap();
    SurfaceView surfaceView;
    TextView progress;
    IMediaApi mediaPlayer;
    String tPath;
    FrameLayout flView;
    private List<String> videoPaths = new ArrayList<>();
    private int index;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    progress.setVisibility(View.VISIBLE);
                    progress.setText(formatTime(mediaPlayer.getProgress()));
                    sendEmptyMessageDelayed(1, 1000);
                    break;
                case 2:
                    Log.e(TAG, "onVideoSizeChanged() called with: width = [" + msg.arg1 + "], height = [" + msg.arg2 + "]");
                    resizeViewView(msg.arg1, msg.arg2);
                    lastW = msg.arg1;
                    lastH = msg.arg2;
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: ");

        int i = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (i == PackageManager.PERMISSION_DENIED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
        } else {
            initData();
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
            initData();
            init();
        }
    }

    private void initData() {
        if (mpStWhat.length == mpStStr.length) {
            for (int i = 0; i < mpStWhat.length; i++) {
                map.put(mpStWhat[i], mpStStr[i]);
            }
        }

        tPath = "/storage/udisk2/岑宁儿-追光者 (《夏至未至》电视剧插曲)(蓝光).mp4";
        String rootPath = "/storage/udisk2/media不同格式/video";
//        String rootPath = "/storage/udisk2/MP4";
//        String rootPath = "/storage/udisk2/多媒体";
        File file = new File(rootPath);
        if (file.exists()) {
            videoPaths.clear();
            for (File listFile : file.listFiles()) {
                if (listFile.isFile()) videoPaths.add(listFile.getAbsolutePath());
            }
        }
        videoPaths.add(0, tPath);
        mediaPlayer = new IjkPlayer();
//        mediaPlayer = new MyPlayer();
    }

    private void init() {
        flView = findViewById(R.id.flView);
        progress = findViewById(R.id.progress);
        surfaceView = findViewById(R.id.surfaceView);
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.i(TAG, "surfaceCreated() called with: holder = [" + holder + "]");
                mediaPlayer.setDisplay(holder);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.i(TAG, "surfaceChanged() called with: holder = [" + holder + "], format = [" + format + "], width = [" + width + "], height = [" + height + "]");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.i(TAG, "surfaceDestroyed() called with: holder = [" + holder + "]");
                mediaPlayer.setDisplay(null);
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.i(TAG, "onPrepared() called with: mp = [" + mp + "]");
                ((TextView) findViewById(R.id.et)).setText(videoPaths.get(getIndex()));
                mediaPlayer.start();
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.i(TAG, "onError() called with: mp = [" + mp + "], what = [" + what + "],  whatStr = [" + map.get(what) + "], extra = [" + extra + "]");
                return true;
            }
        });
        mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                Log.i(TAG, "onInfo() called with: mp = [" + mp + "], what = [" + what + "],  whatStr = [" + map.get(what) + "], extra = [" + extra + "]");
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    handler.sendEmptyMessage(1);
                }
                return true;
            }
        });
        mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                if (width != lastW || height != lastH) {
                    handler.removeMessages(2);
                    handler.sendMessageDelayed(Message.obtain(handler, 2, width, height), 50);
                }
            }
        });
    }

    private String formatTime(long progress) {
        Log.d(TAG, "formatTime() called with: progress = [" + progress + "]");
        progress = progress / 1000;
        return String.format("%02d:%02d:%02d", progress / 60 / 60, progress / 60 % 60, progress % 60);
    }

    int lastW, lastH;
    int dW, dH;

    private void resizeViewView(int width, int height) {
        int fWidth = flView.getWidth();
        int fHeight = flView.getHeight();
        float rate = 1;
        rate = Math.max(1f * width / fWidth, 1f * height / fHeight);
        int desireW = (int) (width / rate);
        int desireH = (int) (height / rate);
        ViewGroup.LayoutParams layoutParams = surfaceView.getLayoutParams();
        layoutParams.width = dW = desireW;
        layoutParams.height = dH = desireH;
        surfaceView.setLayoutParams(layoutParams);
    }

    public void clk(View view) {
        switch (view.getId()) {
            case R.id.play:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    handler.removeMessages(1);
                } else if (mediaPlayer.isPaused()) {
                    mediaPlayer.start();
                    handler.sendEmptyMessage(1);
                } else {
                    ((TextView) findViewById(R.id.et)).setText(videoPaths.get(getIndex()));
                    mediaPlayer.setDataSource(videoPaths.get(getIndex()));
                    mediaPlayer.prepare();
                }
                break;
            case R.id.small:
                changeFlView(false);
                break;
            case R.id.bigger:
                changeFlView(true);
                break;
            case R.id.last:
                playNextOrLast(false);
                break;
            case R.id.next:
                playNextOrLast(true);
                break;
        }
    }

    private void playNextOrLast(boolean next) {
        if (next) index++;
        else index--;
        mediaPlayer.reset();
        mediaPlayer.setDisplay(surfaceView.getHolder());
        mediaPlayer.setDataSource(videoPaths.get(getIndex()));
        mediaPlayer.prepare();
        handler.removeMessages(1);
    }

    private void changeFlView(boolean bigger) {
        int width = flView.getWidth();
        ViewGroup.LayoutParams layoutParams = flView.getLayoutParams();
        layoutParams.width = width + (bigger ? 50 : -50);
        flView.setLayoutParams(layoutParams);
        flView.postDelayed(new Runnable() {
            @Override
            public void run() {
                resizeViewView(mediaPlayer.getVideoWidth(), mediaPlayer.getVideoHeight());
            }
        }, 100);
    }

    private int getIndex() {
        if (index < 0) index = videoPaths.size() - 1;
        else if (index >= videoPaths.size()) index = 0;
        return index;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaPlayer.reset();
        mediaPlayer.release();
    }
}